﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface;
using Ganss.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Dsig;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 资产维修电子流
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CapitalRepairElectronFlowController : ControllerBase
    {
        private ILogger<CapitalRepairElectronFlowController> logger;
        private readonly string ProcessFullName = "AssetsManagement\\EquipmentMaintenance";
        private ICapitalRepairReportFormService capitalRepairReportFormService;
        private IConfiguration configuration;
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";
        private readonly string MailSendUrl = "/api/MailSender/SendMailToQueue";
        private readonly string DepartmentInformationUrl = "/api/ConfigCommon/SearchFinanceDept";

        public CapitalRepairElectronFlowController(ILogger<CapitalRepairElectronFlowController> _logger, 
            ICapitalRepairReportFormService _capitalRepairReportFormService,
            IConfiguration _configuration
            ) 
        {
            logger = _logger;
            capitalRepairReportFormService = _capitalRepairReportFormService;
            configuration = _configuration;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID">流程实例编号</param>
        /// <param name="applicationNumber"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID, string? applicationNumber)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrWhiteSpace(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new CapitalRepairElectronFlowReq();
            var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
            var appNumber = await HttpHelper.GetAsync<string>(url2);
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonConvert.SerializeObject(formDataModel);
            return Ok(result);
        }

        /// <summary>
        /// 返回资产维修电子流报表主数据
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("CapitalRepairReportFormData")]
        [PageList]
        public IActionResult GetCapitalRepairReportFormData(CapitalRepairReportConditionModel inputCondition) 
        {
            var list = capitalRepairReportFormService.GetCapitalRepairReportFormPageList(inputCondition);
            int count = capitalRepairReportFormService.GetCapitalRepairReportFormData(inputCondition).Count();

            var result = ApiResponsePageList<CapitalRepairReportFormModel>.CreatePageListByResult(list, inputCondition.pageIndex, inputCondition.pageSize, count);

            return Ok(result);
        }

        /// <summary>
        /// 新增/修改报表数据
        /// </summary>
        /// <param name="capitalRepairBusinessData"></param>
        /// <returns></returns>
        [HttpPost("SavaCapitalRepairReportFormData")]
        public async Task<IActionResult> SavaCapitalRepairReportFormData(CapitalRepairBusinessDataModel capitalRepairBusinessData)
        {
            int count = 0;
            string _ProcInstId = capitalRepairBusinessData == null ? "0" : capitalRepairBusinessData.ProcInstId;
            try
            {
                if (capitalRepairBusinessData != null)
                {
                    var IsBusinessDataModel = await capitalRepairReportFormService.GetCapitalRepairBusinessDataFind(capitalRepairBusinessData.ProcInstId);
                    if (IsBusinessDataModel != null)
                    {
                        capitalRepairBusinessData.SysId = IsBusinessDataModel.SysId;
                        capitalRepairBusinessData.CreateTime = IsBusinessDataModel.CreateTime;
                        capitalRepairBusinessData.ProcessFolio = capitalRepairBusinessData.ProcessFolio.Trim();
                        count = await capitalRepairReportFormService.EditCapitalRepairBusinessData(capitalRepairBusinessData);
                    }
                    else
                    {
                        capitalRepairBusinessData.SysId = Guid.NewGuid().ToString("N");
                        capitalRepairBusinessData.CreateTime = DateTime.Now;
                        capitalRepairBusinessData.ProcessFolio = capitalRepairBusinessData.ProcessFolio.Trim();
                        count = await capitalRepairReportFormService.AddCapitalRepairBusinessData(capitalRepairBusinessData);
                    }
                }
                logger.LogInformation($"新增报表数据（资产维修电子流）,流程实例号：{_ProcInstId},数量：{count},时间：{DateTime.Now}");
                return Ok(count);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（资产维修电子流）,流程实例号：{_ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }

        }

        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="mailSend"></param>
        /// <returns></returns>
        [HttpPost("MailSend")]
        public async Task<IActionResult> SendMail(MailSendModel mailSend ) 
        {
            var count = 0;
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var url = $"{CommonServiceHost}{MailSendUrl}";
            if (mailSend != null)
            {
                mailSend.createdDate = DateTime.Now;
                count = await HttpHelper.PostAsync<int>(url, JsonConvert.SerializeObject(mailSend));
            }
            return Ok(count);
        }

        /// <summary>
        /// 获取当前人部门信息
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost("DepartmentInfo")]
        public async Task<IActionResult> DepartmentInfo(DepartmentCondition condition)
        {
            var list = new DepartmentInfoPage();
            list.pageSize = condition.pageSize;
            list.pageNum = condition.current;
            list.total = 0;

            if (!string.IsNullOrWhiteSpace(condition.searchCondition))
            {
                var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
                var url = $"{CommonServiceHost}{DepartmentInformationUrl}?searchCondition={condition.searchCondition}";
                var result = await HttpHelper.GetAsync<string>(url);
                var data = JsonConvert.DeserializeObject<List<DepartmentInfoModel>>(result);
                if (data.Any())
                {
                    int _current = (condition.current-1) *  condition.pageSize;
                    list.detData = data.Skip(_current).Take(condition.pageSize).ToList();
                }
                list.total = data.Count;
            }
            return Ok(list);
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="relativePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile")]
        [PageList]
        public async Task<IActionResult> DownloadFile(string relativePath, string fileName)
        {
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            var fileFullPath = $"{fileDir}\\{relativePath}";
            var stream = await System.IO.File.ReadAllBytesAsync(fileFullPath);
            return File(stream, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("CapitalRepairReportExport")]
        [PageList]
        public async Task<IActionResult> CapitalRepairReportExport(CapitalRepairReportConditionModel inputCondition)
        {
            inputCondition.pageIndex = 1;
            inputCondition.pageSize = 65535;
            var list = capitalRepairReportFormService.GetCapitalRepairReportFormPageList(inputCondition);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\资产维修电子流报表{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", list);
            return Ok(filePath);
        }
    }
}
